/*
 * Copyright 2023-present by Damon All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"context"
	"flag"
	"github.com/bytedance/sonic"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/app/server/registry"
	"github.com/cloudwego/hertz/pkg/app/server/render"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/fsnotify/fsnotify"
	"primus/pkg/conf"
	"primus/pkg/license"

	//"github.com/hertz-contrib/cache"
	//"github.com/hertz-contrib/cache/persist"
	"github.com/hertz-contrib/obs-opentelemetry/provider"
	hertztracing "github.com/hertz-contrib/obs-opentelemetry/tracing"
	"github.com/hertz-contrib/registry/nacos"
	"k8s.io/apimachinery/pkg/util/wait"
	"primus/consumer-service/router"
	"primus/pkg/constants"
	nacosCli "primus/pkg/nacos"
	"primus/pkg/util"
	"primus/pkg/util/singleton"
	"time"

	//"github.com/cloudwego/hertz/pkg/app/middlewares/client/sd"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	//"primus/pkg/nacos"
	//nacoscli "github.com/hertz-contrib/registry/nacos"
)

var logFile = "/Users/damon/data/consumer-service/logs/"
var filePath = "/path/to/your/file"
var fileName = "conf/config.yaml"
var configFile = flag.String("envConfig", fileName, "config for the server")

func readFileByEnv() {
	//var configFile = flag.String("envConfig", fileName, "config for the server")

	//flag.Parse()

	config, err := conf.ParseFromYAML(*configFile)
	if err != nil {
		hlog.Error(err)
	}
	hlog.Info("config: ", config)
	//把内容对象赋值给一个常量
	//conf.EnvConfig = conf.Config{TestKey: config.TestKey}
}


func main() {
	//hlog.SetLogger(logrus.NewLogger())
	//与上面不可兼得，只能按照一种格式输出
	hlog.SetOutput(util.NewLogger(logFile))
	hlog.SetLevel(hlog.LevelInfo)
	stop := make(chan struct{})
	//服务启动后会检测5分钟检测一次软件授权，第一次看授权,全局变量
	go wait.Until(license.LicenceChecker, 5*time.Minute, stop)
	readFileByEnv()
	p := provider.NewOpenTelemetryProvider(
		provider.WithServiceName(constants.ConsumerServiceName),
		provider.WithExportEndpoint("121.37.173.206:4317"), //("localhost:4317"),
		provider.WithInsecure(),
	)
	defer func(ctx context.Context, p provider.OtelProvider) {
		_ = p.Shutdown(ctx)
	}(context.Background(), p)

	//tracer.InitJaeger(constants.ConsumerServiceName)

	render.ResetJSONMarshal(sonic.ConfigStd.Marshal)
	conf, err := nacosCli.NewNacosConfig("121.37.173.206", 8848, "")
	if err != nil {
		hlog.Error(err)
	}

	singleton.GetHttpCli()

	// 开始监听文件变化事件
	go wait.Until(watchFile, 1*time.Second, stop)

	tracer, cfg := hertztracing.NewServerTracer()
	h := server.Default(
		tracer,
		server.WithHostPorts(":10000"),
		server.WithRegistry(nacos.NewNacosRegistry(conf), &registry.Info{
			ServiceName: constants.ConsumerServiceName,
			Addr:        utils.NewNetAddr("tcp", util.GetIpAddr()+":10000"),
			Weight:      10,
			Tags:        nil,
		}),
	)
	h.Use(hertztracing.ServerMiddleware(cfg))

	// 设置全局的缓存过期时间（会被更细粒度的设置覆盖）
	//memoryStore := persist.NewMemoryStore(1 * time.Minute)
	// 设置针对以 URI 为 Key 的缓存过期时间
	//h.Use(cache.NewCacheByRequestURI(memoryStore, 2*time.Second))
	//h.Use(cache.NewCacheByRequestPath(memoryStore, 2*time.Second))

	router.Init(h)
	h.Spin()
}

func watchFile() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		hlog.Error("watcher error: ", err)
	}
	defer watcher.Close()

	// 添加要监视的文件
	err = watcher.Add(fileName)
	if err != nil {
		hlog.Error("watcher error: ", err)
	}

	select {
	case event, ok := <-watcher.Events:
		if !ok {
			hlog.Error(ok)
			return
		}
		if event.Op&fsnotify.Write == fsnotify.Write {
			hlog.Debug("update config")
			readFileByEnv()
		}
	case err, ok := <-watcher.Errors:
		if !ok {
			return
		}
		hlog.Error("watcher error: ", err)
	}
}
